﻿using HttpCode.Core;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Dan.Common.CusException;

namespace Dan.Common
{
    public class UrlRequest
    {                    
        /// <summary>
        /// dictionary to querystring
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        public static string DictToStr(Dictionary<object,object> dict)
        {
            StringBuilder sb = new StringBuilder();
            foreach(var item in dict)
            {
                sb.Append($"{item.Key}={item.Value}&");
            }
            return sb.ToString().TrimEnd('&');
            
        }
        
        /// <summary>
        /// post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postDataStr"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static string HttpPostNew(string url, string postDataStr, Dictionary<string, string> header = null)
        {
            var h = new WebHeaderCollection();
            if (header != null)
            {
                foreach (var item in header)
                {
                    h.Add(item.Key, item.Value);
                }
            }

            HttpHelpers http = new HttpHelpers(); //发起请求具体对象
            var result = http.GetHtml(new HttpItems
            {
                Url = url,
                Postdata = postDataStr,
                Header = h,
            });

            var str = result.Html;
            return str;
        }

        /// <summary>
        /// 调用远程HTTPPOST请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr">传参方式string.Format("{{ \"paraname\": {0}, \"para\": {1}, \"para\": {2}, \"para\": {3}, \"para\": \"{4}\" }}"),</param>
        /// <param name="header">头部信息</param>
        /// <param name="ContentType"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr, Dictionary<string, string> header = null, string ContentType = "application/x-www-form-urlencoded")
        {
            var request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = ContentType;
            if (header != null)
            {
                foreach (var item in header)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }

            byte[] buffer = Encoding.UTF8.GetBytes(postDataStr);
            request.ContentLength = buffer.Length; //Encoding.UTF8.GetByteCount(postDataStr);

            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream myResponseStream = response.GetResponseStream();
            
            if (myResponseStream == null)
            {
                throw new MsgException("请求失败");
            }
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

            string retString = myStreamReader.ReadToEnd();
            // myStreamWriter.Close();
            myRequestStream.Close();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// post
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr">传参方式string.Format("{{ \"paraname\": {0}, \"para\": {1}, \"para\": {2}, \"para\": {3}, \"para\": \"{4}\" }}"</param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        private static string HttpPost(string Url, string postDataStr, ref CookieContainer cookie)
        {
            var request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            
            if (myResponseStream == null)
            {
                throw new MsgException("请求失败");
            }
            
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// get
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr">传参方式string.Format("{{ \"paraname\": {0}, \"para\": {1}, \"para\": {2}, \"para\": {3}, \"para\": \"{4}\" }}"</param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr, Dictionary<string, string> header = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            if (header != null)
            {
                foreach (var item in header)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();

            if (myResponseStream == null)
            {
                throw new MsgException("请求失败");
            }
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

    }
}
